package cc.mrbird.web.service.impl;

import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.system.domain.MidStudent;
import cc.mrbird.system.domain.Student;
import cc.mrbird.web.dao.MidStudentMapper;
import cc.mrbird.web.dao.StudentMapper;
import cc.mrbird.web.domain.RespImport;
import cc.mrbird.web.hanlder.MidStudentExcelHandler;
import cc.mrbird.web.hanlder.StudentExcelHandler;
import cc.mrbird.web.service.MidStudentService;
import cc.mrbird.web.service.StudentService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service("midStudentService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MidStudentServiceImpl extends BaseService<MidStudent> implements MidStudentService {

    private static final Logger log = LoggerFactory.getLogger(MidStudentServiceImpl.class);

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MidStudentMapper midStudentMapper;

    @Override
    public void addMidStudent(MidStudent midStudent,String midUserName) {
        midStudent.setCreatedTime(new Date());
        midStudent.setUpdatedTime(new Date());
        midStudent.setUserName(midUserName);
        midStudentMapper.insertMidStudent(midStudent);
        log.info("插入学生信息成功");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void updateMidStudent(MidStudent midStudent) {

        midStudent.setUpdatedTime(new Date());
        midStudentMapper.updateMidStudent(midStudent);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void deleteMidStudents(String studentIds) {

        List<String> list = Arrays.asList(studentIds.split(","));
        midStudentMapper.deleteByIds(list);
    }

    @Override
    public RespImport ImportMidStudent(MultipartFile file, String userName) {

        ImportParams importParams = new ImportParams();      // 数据处理
        IExcelDataHandler<MidStudent> handler = new MidStudentExcelHandler();
        handler.setNeedHandlerFields(new String[] { "考生号" });// 注意这里对应的是excel的列名。也就是对象上指定的列名。
        importParams.setDataHanlder(handler);

        // 需要验证
        importParams.setNeedVerfiy(true);

        List<MidStudent> successList = null;
        List<MidStudent> failList = null;
        int successNum = 0,failureNum =0,repeatNum = 0;
        RespImport respImport = new RespImport();
        String tempRepeatStudentId = null;
        String tempFailureStudentId = null;
        String tempRepeatIDNumber = null;
        String tempFailureIDNumber = null;
        try {
            ExcelImportResult<MidStudent> result = ExcelImportUtil.importExcelMore(file.getInputStream(), MidStudent.class,
                    importParams);

            successList = result.getList();
            failList = result.getFailList();

            log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
            log.info("验证通过的数量:" + successList.size());
            log.info("验证未通过的数量:" + failList.size());

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        for ( MidStudent midStudent : successList) {
            midStudent.setUserName(userName);
            midStudent.setCreatedTime(new Date());
            midStudent.setUpdatedTime(new Date());
            MidStudent resultId = midStudentMapper.findById(midStudent.getMidStudentId());
            MidStudent resultIdNum = midStudentMapper.findByIdNumber(midStudent.getIdNumber());
            if (resultId != null){
                repeatNum++;
                failureNum++;
                tempRepeatStudentId += resultId.getMidStudentId()+"、";
                tempRepeatStudentId = tempRepeatStudentId.replace("null","");
                respImport.setRepeatStudentId(tempRepeatStudentId);
                log.info("考生号已存在:" + resultId.getMidStudentId() );
            }
            if (resultIdNum != null){
                repeatNum++;
                failureNum++;
                tempRepeatIDNumber += resultIdNum.getIdNumber()+"、";
                tempRepeatIDNumber = tempRepeatIDNumber.replace("null","");
                respImport.setRepeatIDNumber(tempRepeatIDNumber);
                log.info("身份证号："+resultIdNum.getIdNumber()+"已存在" );
            }
            if (resultId == null && resultIdNum == null){
                successNum++;
                midStudentMapper.insertMidStudent(midStudent);
            }
            log.info("插入学生信息成功");
            log.info("成功列表信息:ID=" + midStudent.getMidStudentId() + midStudent.getName() );
        }
        for (MidStudent midStudent : failList) {
            /*midStudent.setStatus("可疑");
            midStudent.setUserName(userName);
            midStudent.setCreatedTime(new Date());
            midStudent.setUpdatedTime(new Date());
            MidStudent resultId = midStudentMapper.findById(midStudent.getMidStudentId());
            MidStudent resultIdNum = midStudentMapper.findByIdNumber(midStudent.getIdNumber());
            if (resultId != null)
                log.info("考生号:" + resultId.getMidStudentId() + "已存在" );
            if (resultIdNum != null)
                log.info("身份证号："+resultIdNum.getIdNumber()+"已存在" );
            if (resultId == null && resultIdNum == null)
                midStudentMapper.insertMidStudent(midStudent);*/
            tempFailureStudentId += midStudent.getMidStudentId()+"、";
            tempFailureStudentId = tempFailureStudentId.replace("null","");
            respImport.setFailureStudentId(tempFailureStudentId);
            tempFailureIDNumber += midStudent.getIdNumber()+"、";
            tempFailureIDNumber = tempFailureIDNumber.replace("null","");
            respImport.setFailureIDNumber(tempFailureIDNumber);
            //log.info("失败信息:" + midStudent.getMidStudentId() + midStudent.getName() );
            failureNum++;
        }
        respImport.setSuccessNum(successNum);
        respImport.setFailureNum(failureNum);
        return respImport;
    }

    @Override
    public List<MidStudent> findMidStudentAll() {
        return midStudentMapper.findMidStudentAll();
    }

    @Override
    public List<MidStudent> findMidStudentByCondition(MidStudent midStudent) {
        return midStudentMapper.findMidStudentByCondition(midStudent);
    }

    /**
     * 根据id查找考生信息
     * @param studentId
     * @return
     */
    @Override
    public MidStudent findById(String studentId) {
        return midStudentMapper.findById(studentId);
    }

    /**
     * 根据id查找考生信息
     * @param idNumber
     * @return
     */
    @Override
    public MidStudent findByIdNumber(String idNumber) {
        return midStudentMapper.findByIdNumber(idNumber);
    }

}
